<?php
class Login extends CI_Controller {
    private $pass = '';
    public function __construct() {
        parent::__construct ();
        $this->load->helper ( array (
            'form',
            'url'
        ) );
        $this->load->library('session');
        $this->load->database();
    }
    public function index() {
        $login_error_msg = $this->session->flashdata('login_error_msg');
        $this->load->view ( 'login/login', ['login_error_msg' => $login_error_msg]);
    }
    public function formsubmit() {
        $this->load->library ( 'form_validation' );

        $this->form_validation->set_rules ( 'username', '账号', 'required', ['required' => '*账号必须填写']);
        $this->form_validation->set_rules ( 'password', '密码', 'required', ['required' => '*密码必须填写']);
        if ($this->form_validation->run () == FALSE) {
            $this->load->view ( 'login/login' );
        } else {
            if (isset ( $_POST ['submit'] ) && ! empty ( $_POST ['submit'] )) {
                $data = array (
                    'user' => $_POST ['username'],
                    'pass' => md5($_POST ['password'])
                );
                $newdata = array(
                    'username'  =>  $data ['user'] ,
                    'userip'     => $_SERVER['REMOTE_ADDR'],
                    'luptime'   =>time()
                );
                if ($_POST ['submit'] == 'login') {
                    $query = $this->db->get_where ( 'uc_user', array (
                        'user' => $data ['user']
                    ), 1, 0 );

                    foreach ( $query->result () as $row ) {
                        $pass = $row->pass;
                        $id = $row->id;
                     }
                    if (isset($pass) && $pass == $data ['pass']) {

                        $this->session->set_userdata(['admin_id' => $id]);
                        $this->load->view ( 'home/index', $data );
                    } else {
                        $this->session->set_flashdata('login_error_msg', '*账号或密码错误');
                        redirect('login/index');
                    }
                } else if ($_POST ['submit'] == 'register') {

                    $this->session->set_userdata($newdata);
                    $this->db->insert ( 'uc_user', $data );
                    $this->load->view ( 'usercenter', $data );
                } else {
                    $this->session->sess_destroy();
                    $this->load->view ( 'login/login' );
                }
            }
        }
    }
}